package com.chinawlx.wlxteacher.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXClazzDynamicBean;
import com.chinawlx.wlxteacher.ui.adapter.WLXDynamicAdapter;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXNetUtil;
import com.chinawlx.wlxteacher.utils.WLXTeacherConstant;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_grade_notice;
import com.chinawlx.wlxteacher.wlx_grade_noticeDao;
import com.google.gson.Gson;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.refreshlayout.BGAMeiTuanRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import rx.Subscriber;

/**
 * 班级动态界面
 * <p>
 * Created by yyc on 2016/8/2.
 */
public class WLXClazzDynamicsFragment extends WLXBaseFragment implements BGARefreshLayout
        .BGARefreshLayoutDelegate {

    private int paging_index = 1;//分页索引
    private int paging_size = 10;//每页大小
    private boolean mHasMoreData = true;

    @BindView(R.id.rl_modulename_refresh)
    BGARefreshLayout mRefreshLayout;
    @BindView(R.id.rl_container_empty)
    RelativeLayout mRlContainerEmpty;
    @BindView(R.id.tv_msg)
    TextView mTvMsg;

    @BindView(R.id.listview_clazz_dynamic)
    ListView dynamicListView;
    private String grade_id;
    private Gson gson;
    private WLXLoadingFragment wlxLoadingFragment;
    private WLXDynamicAdapter wlxDynamicAdapter;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_clazz_dynamic, null);
        ButterKnife.bind(this, view);

        init();
        return view;
    }

    private void init() {
        initView();
    }




    private List<wlx_grade_notice> gradeNotices;


    private void initView() {
        grade_id = getArguments().getString(WLXTeacherConstant.GRADE_ID);
        initAdapter();
        initRefreshLayout();
        mRefreshLayout.beginRefreshing();
    }

    private void initAdapter() {
        wlxDynamicAdapter = new WLXDynamicAdapter(mContext);
        dynamicListView.setAdapter(wlxDynamicAdapter);
    }
    //--------刷新内容 start---------

    private void initRefreshLayout() {
        mRefreshLayout.setDelegate(this);
        BGAMeiTuanRefreshViewHolder meiTuanRefreshViewHolder = new BGAMeiTuanRefreshViewHolder
                (this.getContext(), true);
        meiTuanRefreshViewHolder.setPullDownImageResource(R.drawable.yuanq);
        meiTuanRefreshViewHolder.setChangeToReleaseRefreshAnimResId(R.drawable
                .bga_refresh_mt_change_to_release_refresh);
        meiTuanRefreshViewHolder.setRefreshingAnimResId(R.drawable.bga_refresh_mt_refreshing);

        mRefreshLayout.setRefreshViewHolder(meiTuanRefreshViewHolder);
    }

    //开始刷新
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.CheckNetwork(getActivity())) {
            paging_index = 1;
            requestDataFromNet();
        } else {
//            WLXCustomToast.show("无网络!");
            mRefreshLayout.endRefreshing();
            initDataFromDataBase();
        }
    }


    //处理上拉加载,在这里上拉加载更多,
    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.CheckNetwork(getActivity())) {
            if (mHasMoreData) {
                paging_index++;
                requestDataFromNet();
                return true;
            } else {
                WLXCustomToast.show("没有更多数据");
                return false;
            }
        } else {
//            WLXCustomToast.show("无网络!");
            initDataFromDataBase();
            return false;
        }
    }

    //-----------刷新 end------


    private void requestDataFromNet() {
        wlxLoadingFragment = WLXLoadingFragment.getInstance();
        wlxLoadingFragment.show(getActivity().getSupportFragmentManager(), "");
        WLXHttpRxHelper.getInstance().getClazzDynamic(grade_id, paging_index + "", paging_size +
                "", new
                Subscriber<WLXClazzDynamicBean>() {

                    @Override
                    public void onCompleted() {
                        initDataFromDataBase();
                        wlxLoadingFragment.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }

                    @Override
                    public void onNext(WLXClazzDynamicBean wlxClazzDynamicBean) {
                        insert2Db(wlxClazzDynamicBean);
                    }
                });
    }

    private void initDataFromDataBase() {
        gradeNotices = WLXGreenDaoUtil.getGradeNoticeDao().queryBuilder()
                .where(wlx_grade_noticeDao.Properties
                                .Teacher_user_id.eq(WLXConstant.USER_ID),
                        wlx_grade_noticeDao.Properties.Grade_id.eq(grade_id))
                .orderAsc().offset((paging_index - 1) * paging_size).limit(paging_size).list();
        //是否有更多数据
        mHasMoreData = gradeNotices.size() != 0;
        if (paging_index == 1) {//下拉刷新,直接加载所有的未点评数据
            mRefreshLayout.endRefreshing();
            wlxDynamicAdapter.setData(gradeNotices);
            wlxDynamicAdapter.notifyDataSetChanged();

            if (gradeNotices.size() == 0) {
                mRefreshLayout.setVisibility(View.GONE);
                mRlContainerEmpty.setVisibility(View.VISIBLE);
                mTvMsg.setText("暂无数据");
                return;
            }

        } else {
            mRefreshLayout.endLoadingMore();
            //上拉刷新,只需要刷新历史数据
            if (mHasMoreData) {
                int count = wlxDynamicAdapter.getCount();
                wlxDynamicAdapter.addData(gradeNotices);
                wlxDynamicAdapter.notifyDataSetChanged();
                dynamicListView.setSelection(count);
            } else {
                WLXCustomToast.show("没有更多数据");
            }
        }
    }

    private void insert2Db(WLXClazzDynamicBean wlxClazzDynamicBean) {
        List<WLXClazzDynamicBean.DataBean.GradeNoticeListBean> grade_notice_list
                = wlxClazzDynamicBean.getData().getGrade_notice_list();
        gson = new Gson();
        for (WLXClazzDynamicBean.DataBean.GradeNoticeListBean gradeNoticeListBean :
                grade_notice_list) {
            String grade_notice_id = Integer.toString(gradeNoticeListBean.getId());
            int grade_id = gradeNoticeListBean.getGrade_id();
            int teacher_user_id = gradeNoticeListBean.getTeacher_user_id();
            //定义一个String字符串用来拼接id保存到数据库
            String family_user_ids = "";
            List<String> family_user_id = gradeNoticeListBean.getFamily_user_ids();
            for (String id : family_user_id) {
                family_user_ids += id + ",";
            }
            int resource_id = gradeNoticeListBean.getResource_id();
            String content = gradeNoticeListBean.getContent();
            String type_code = gradeNoticeListBean.getType().getKey();
            String status_code = gradeNoticeListBean.getStatus().getKey();
            String extend_info = gson.toJson(gradeNoticeListBean.getExtend());
            long last_modified_date = WLXDateUtil.getStringToDate
                    (gradeNoticeListBean.getLast_modified_date());
            long creation_date = WLXDateUtil.getStringToDate(gradeNoticeListBean
                    .getCreation_date());
            //------------------存储wlx_grade_notice表-----------------
            wlx_grade_notice wlx_grade_notice = new wlx_grade_notice
                    (grade_notice_id, grade_id, teacher_user_id, family_user_ids,
                            resource_id, content, type_code, status_code,
                            extend_info, last_modified_date, creation_date);

            List<wlx_grade_notice> gradeNoticeList = WLXGreenDaoUtil
                    .getGradeNoticeDao()
                    .queryBuilder().where
                            (wlx_grade_noticeDao.Properties.Grade_notice_id.eq
                                    (grade_notice_id)).list();
            if (gradeNoticeList.size() > 0) {
                if (last_modified_date > gradeNoticeList.get(0)
                        .getLast_modified_date()) {
                    WLXGreenDaoUtil.getGradeNoticeDao().update(wlx_grade_notice);
                }
            } else {
                WLXGreenDaoUtil.getGradeNoticeDao().insert(wlx_grade_notice);
            }
        }
    }

}

